import { Hono } from 'hono'
import { PluginService } from '@/services/pluginService'
import { optionalAuthMiddleware } from '@/middleware/auth'
import { asyncHandler } from '@/middleware/errorHandler'

const plugins = new Hono()
const pluginService = new PluginService()

// 可选认证中间件（用于统计等功能）
plugins.use('*', optionalAuthMiddleware())

// 获取插件列表
plugins.get('/', asyncHandler(async (c) => {
  const query = {
    search: c.req.query('search'),
    category: c.req.query('category'),
    tags: c.req.query('tags')?.split(','),
    featured: c.req.query('featured') ? c.req.query('featured') === 'true' : undefined,
    verified: c.req.query('verified') ? c.req.query('verified') === 'true' : undefined,
    sort: c.req.query('sort') as 'downloads' | 'rating' | 'updated' | 'created',
    order: c.req.query('order') as 'asc' | 'desc',
    page: parseInt(c.req.query('page') || '1'),
    limit: parseInt(c.req.query('limit') || '20')
  }

  const result = await pluginService.getPluginList(query)

  return c.json({
    success: true,
    data: result,
    message: 'Plugins retrieved successfully'
  })
}))

// 获取插件详情 (通过ID或名称)
plugins.get('/:identifier', asyncHandler(async (c) => {
  const identifier = c.req.param('identifier')

  // 检查是否是ID格式 (cuid格式: 以c开头的25字符字符串)
  const isId = /^c[a-z0-9]{24}$/.test(identifier)

  let plugin
  if (isId) {
    plugin = await pluginService.getPluginDetailsById(identifier)
  } else {
    plugin = await pluginService.getPluginDetails(identifier)
  }

  return c.json({
    success: true,
    data: { plugin },
    message: 'Plugin details retrieved successfully'
  })
}))

// 获取插件版本列表
plugins.get('/:name/versions', asyncHandler(async (c) => {
  const pluginName = c.req.param('name')

  const result = await pluginService.getPluginVersions(pluginName)

  return c.json({
    success: true,
    data: result,
    message: 'Plugin versions retrieved successfully'
  })
}))

// 下载插件包
plugins.get('/:name/download/:version', asyncHandler(async (c) => {
  const pluginName = c.req.param('name')
  const version = c.req.param('version')

  const downloadInfo = await pluginService.downloadPlugin(pluginName, version)

  // 设置下载响应头
  c.header('Content-Type', 'application/zip')
  c.header('Content-Disposition', `attachment; filename="${pluginName}-${version}.zip"`)
  c.header('Content-Length', downloadInfo.fileSize.toString())

  // 返回文件流
  return c.body(downloadInfo.fileStream)
}))

// 获取插件Manifest
plugins.get('/:name/manifest/:version', asyncHandler(async (c) => {
  const pluginName = c.req.param('name')
  const version = c.req.param('version')

  const manifest = await pluginService.getPluginManifest(pluginName, version)

  return c.json({
    success: true,
    data: { manifest },
    message: 'Plugin manifest retrieved successfully'
  })
}))

export default plugins
